package com.ice.body.business.controller;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.ice.body.business.model.ReagentAreaModel;
import com.ice.body.business.vo.ReagentStockVo;
import com.ice.body.log.model.LogDestroy;
import com.ice.body.business.model.ReagentStock;
import com.ice.body.business.model.WareHouseModel;
import com.ice.body.business.service.ReagentAreaService;
import com.ice.body.business.service.ReagentStockService;
import com.ice.body.business.service.WareHouseService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Api;
import com.ice.base.controller.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import com.github.pagehelper.PageHelper;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

import com.ice.base.result.ResponseResult;
import com.ice.base.result.AjaxResult;

/**
 * Created with GuoYanBin.
 * Description:
 * Date: 2025-11-22
 * Time: 10:15
 */
@RestController
@Slf4j
@Api(tags = "业务接口-库存试剂")
public class ReagentStockController extends BaseController{
    //---------------------------业务接口-库存试剂-----------------------start
    @Resource
    private ReagentStockService reagentStockService;
    @Resource
    private WareHouseService wareHouseService;
    @Resource
    private ReagentAreaService reagentAreaService;


    @ApiOperation(value = "库存试剂-批次号更新浓度")
    @PostMapping("/api/ReagentStock/batchUpdateImpurity")
    public AjaxResult<ReagentStock> batchUpdateImpurity( ReagentStock model){
        String batchNo = model.getBatchNo();
        log.info("批量修改浓度:批次号："+ model.getBatchNo() +",浓度值："+ model.getImpurity());
        AjaxResult r = ResponseResult.success();
        if(StringUtils.isEmpty(batchNo)){
            return AjaxResult.error("batchNo 不能为空");
        }
        try{
            reagentStockService.batchUpdateImpurity(model);
        }catch (Exception e){
            e.printStackTrace();
            r = ResponseResult.error();
        }
        return r;
    }



    @ApiOperation(value = "库存试剂-根据epc 查询试剂信息")
    @PostMapping("/api/ReagentStock/getByEpcCode")
    public AjaxResult<ReagentStock> getByEpcCode(@RequestBody ReagentStock model){
        log.info("epc查询试剂:"+ model.getEpcCode());
        AjaxResult r = ResponseResult.success();
        String epcCode = model.getEpcCode();
        if(StringUtils.isEmpty(epcCode)){
            return AjaxResult.error("epcCode 不能为空");
        }
        try{
            ReagentStock stock = reagentStockService.getByEpcCode(epcCode);
            r.setData(stock);
        }catch (Exception e){
            e.printStackTrace();
            r = ResponseResult.error();
        }
        return r;
    }



    @ApiOperation(value = "业务接口-库存试剂-手动入库")
    @PostMapping("/api/ReagentStock/enterWarehouse")
    public AjaxResult enterWarehouse(ReagentStock stock, @RequestParam("epcCode") String epcCode){
        AjaxResult result = ResponseResult.error();
        if(reagentStockService.checkReagentInWarehouse(stock)>0){
            result.setMsg("该药品在仓库中已存在!");
            return  result;
        }
        WareHouseModel wareHouseModel = wareHouseService.selectById(stock.getWarehouseId());
        if(null ==wareHouseModel){
            result.setMsg("库房不存在");
            return result;
        }
/*        ReagentAreaModel reagentAreaModel = reagentAreaService.selectById(stock.getAreaId());
        if(null != reagentAreaModel){
            stock.setAreaName(reagentAreaModel.getAreaName());
        }*/
        try{
            if(reagentStockService.enterWarehouse(stock)){
                result = ResponseResult.success();
            }else{
                result.setMsg("入库失败");
            }

        }catch (Exception e){
            result = ResponseResult.error();
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 手动出库
     */
    @ApiOperation(value = "业务接口-库存试剂-手动出库")
    @PostMapping("/api/ReagentStock/outWarehouse")
    public AjaxResult outWarehouse(@RequestParam("epcCode") String epcCode) {
        AjaxResult result = ResponseResult.error();
        Map<String, Object> map = new HashMap<>();
        try{  ReagentStock model = reagentStockService.getByEpcCode(epcCode);
            if(null != model && model.getState().equals("2")){
                result.setMsg("该产品已经是借出状态！");
                return result;
            }
            if (reagentStockService.outWarehouse(model)) {
                result = ResponseResult.success();
            } else {
                result.setMsg("药品出库失败!");
            }
            result.setData(map);
        }catch (Exception e){
            e.printStackTrace();
        }

        return result;
    }

/*    @ApiOperation(value = "业务接口-库存试剂-新增")
    @PostMapping("/api/ReagentStock/insert")
    public Result<ReagentStockModel> insert_ReagentStock(ReagentStockModel model) {
        Result r = ResponseResult.success();
        try{
            reagentStockService.insert(model);
        }catch (Exception e){
            e.printStackTrace();
            r = ResponseResult.error();
        }
        return r;
    }*/

/*    @ApiOperation(value = "业务接口-库存试剂-删除")
    @PostMapping("/api/ReagentStock/deleteById")
    public Result<ReagentStockModel>  deleteById_ReagentStock(@RequestParam("id") String id) {
        Result r = ResponseResult.success();
        try{
            reagentStockService.delete(id);
        }catch (Exception e){
            e.printStackTrace();
            r = ResponseResult.error();   
        }
        return r;
    }*/

    @ApiOperation(value = "库存试剂-销毁")
    @PostMapping("/api/ReagentStock/destroy")
    public AjaxResult<T> destroy(LogDestroy model) {
        System.out.println("试剂销毁："+model.getEpcCode());
        AjaxResult r = AjaxResult.success();
        try{
            reagentStockService.destroy(model);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error();
        }
        return r;
    }

    @ApiOperation(value = "库存试剂-更新")
    @PostMapping("/api/ReagentStock/updateById")
    public AjaxResult<ReagentStock> update_ReagentStock(ReagentStock model) {
        AjaxResult r = ResponseResult.success();
        try{
            ReagentAreaModel reagentAreaModel = reagentAreaService.selectById(model.getAreaId());
            if(null != reagentAreaModel){
                model.setAreaName(reagentAreaModel.getAreaName());
            }
     /*       WareHouseModel wareHouseModel = wareHouseService.selectById(model.getWarehouseId());
            if(null == wareHouseModel){
                r.setMsg("库房不存在");
                return r;
            }*/

            reagentStockService.update(model);
        }catch (Exception e){
            e.printStackTrace();
            r = ResponseResult.error();
        }
        return r;
    }

    @ApiOperation(value = "库存试剂-查询一个")
    @PostMapping("/api/ReagentStock/selectById")
    public AjaxResult<ReagentStock> selectById_ReagentStock(@RequestParam("id") String id) {
        AjaxResult r = ResponseResult.success();
        try{
           ReagentStock model = reagentStockService.selectById(id);
           r.setData(model);
        }catch (Exception e){
            e.printStackTrace();
            r = ResponseResult.error();   
        }
        return r;
    }

/*    @ApiOperation(value = "库存试剂-查询多个")
    @PostMapping("/api/ReagentStock/selectAll")
    public Result<ReagentStockModel> selectList_ReagentStock(ReagentStockModel model) {
        Result r = ResponseResult.success();
        try{
           List<ReagentStockModel> list = reagentStockService.selectListByModel(model);
           r.setData(list);
        }catch (Exception e){
            e.printStackTrace();
            r = ResponseResult.error();   
        }
        return r;
    }*/

    @ApiOperation(value = "库存试剂-查询分页")
    @PostMapping("/api/ReagentStock/selectListByPageHelper")
    public AjaxResult<ReagentStock> selectListByPageHelper_ReagentStock(
                                                                        @RequestParam(name = "pageSize") Integer pageSize,
                                                                        @RequestParam(name = "pageNum") Integer pageNum,
                                                                        ReagentStock model){
        AjaxResult r = ResponseResult.success();
        ArrayList list;
        try{
           PageHelper.startPage(pageNum, pageSize);
           list = reagentStockService.selectListByModel(model);
           getReturnResultByPage(r,list);
        }catch (Exception e){
            e.printStackTrace();
            r = ResponseResult.error();   
        }
        return r;
    }


    @ApiOperation(value = "库存试剂-危化品汇总")
    @PostMapping("/api/ReagentStock/selectTotal")
    public AjaxResult<ReagentStockVo> selectTotal(@RequestParam(name = "pageSize") Integer pageSize,
                                                  @RequestParam(name = "pageNum") Integer pageNum
                                                  ){
        AjaxResult r = ResponseResult.success();
        try{
            PageHelper.startPage(pageNum, pageSize);
            ArrayList<ReagentStockVo> list = reagentStockService.selectTotal();
            getReturnResultByPage(r,list);
        }catch (Exception e){
            e.printStackTrace();
            r = ResponseResult.error();
        }
        return r;
    }



    @ApiOperation(value = "过期预警-查询分页")
    @PostMapping("/api/ReagentStock/getExpireWarning")
    public AjaxResult<ReagentStock> getExpireWarning(
                    @RequestParam(name = "pageSize") Integer pageSize,
                    @RequestParam(name = "pageNum") Integer pageNum){
        AjaxResult r = ResponseResult.success();
        List list;
        try{
            PageHelper.startPage(pageNum, pageSize);
            list = reagentStockService.getExpireWarning();
            getReturnResultByPage(r,list);
        }catch (Exception e){
            e.printStackTrace();
            r = ResponseResult.error();
        }
        return r;
    }
    //-------------

    @ApiOperation(value = "过期预警-删除")
    @PostMapping("/api/ReagentStock/deleteExpire")
    public AjaxResult<T> deleteExpire(@RequestParam(name = "id") Integer id){
        AjaxResult r = ResponseResult.success();
        try{
             reagentStockService.deleteExpire(id);
        }catch (Exception e){
            e.printStackTrace();
            r = ResponseResult.error();
        }
        return r;
    }
    //---------------------------业务接口-库存试剂-----------------------end

    @ApiOperation(value = "库存试剂-导出")
    @GetMapping("/api/ReagentStock/export")
    public void export(HttpServletResponse response){

        try{
           // PageHelper.startPage(pageNum, pageSize);
            //list = reagentStockService.selectListByModel(model);
            ArrayList list= reagentStockService.selectAll();
            // 通过工具类创建writer
            ExcelWriter writer = ExcelUtil.getWriter();

            //自定义标题别名
            writer.addHeaderAlias("warehouseName", "库房名称");
            writer.addHeaderAlias("cName", "试剂名称");
            writer.addHeaderAlias("casNo", "casNo");
            writer.addHeaderAlias("epcCode", "epc编码");
            writer.addHeaderAlias("state", "试剂状态:1在库;2借出;0销毁9过期");
            writer.addHeaderAlias("expireTimeEnd", "有效期至");
            writer.addHeaderAlias("leftWeigh", "剩余重量");

            // 合并单元格后的标题行，使用默认标题样式
            writer.merge(7, "库存试剂");
            // 一次性写出内容，使用默认样式，强制输出标题
            writer.write(list, true);
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
            String fileName = new String("库存试剂.xls".getBytes(), "ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            ServletOutputStream out = response.getOutputStream();
            writer.flush(out, true);
            // 关闭writer，释放内存
            writer.close();
            //此处记得关闭输出Servlet流
            IoUtil.close(out);

        }catch (Exception e){
            e.printStackTrace();
        }
    }




}
